package com.example.mall

import android.content.Intent
import android.icu.text.Transliterator.Position
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.ImageView
import android.widget.ListView
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.mall.adapter.UserListAdapter
import com.example.mall.dao.UserDao
import com.example.mall.entity.User
import com.example.mall.network.ServiceCreator
import com.example.mall.network.UserService
import com.example.mall.util.ToastUtil
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class LoginActivity : AppCompatActivity(), View.OnClickListener, AdapterView.OnItemClickListener {
    var et_phone : EditText? = null
    var et_password : EditText? = null
    var btn_login : Button? =null
    var tv_management : TextView? = null
    var userList : List<User>? =null
    var lv_user : ListView? = null
    var dialog : AlertDialog? = null
    var ck_remember : CheckBox? = null
    var userDao : UserDao? = null
    var app : MyApplication?= null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_login)
        app = application as MyApplication
        et_phone = findViewById(R.id.et_phone)
        et_password = findViewById(R.id.et_password)
        btn_login = findViewById(R.id.btn_login)
        tv_management = findViewById(R.id.tv_management)
        ck_remember = findViewById(R.id.ck_remember)

        val textWatcher = object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                //只有当两个输入框都有数据时按钮才可用
                updateButtonState()
            }
        }

        btn_login?.setOnClickListener(this)
        et_phone?.addTextChangedListener(textWatcher)
        et_password?.addTextChangedListener(textWatcher)
        tv_management?.setOnClickListener(this)
        //从SQLite获取用户信息并根据情况自动添加默认账号
        userDao = (application as MyApplication).getUserDB().bookDao()
        userList = userDao?.queryAll()
        if(userList?.size!! > 0) {
            et_phone?.setText(userList?.get(0)?.phone)
            if (userList?.get(0)?.remember == true) {
                et_password?.setText(userList?.get(0)?.password)
            }
            ck_remember?.isChecked = userList?.get(0)?.remember == true
        }
    }

    override fun onClick(v: View?) {
        when(v?.id){
            R.id.btn_login -> {
                loginCheck()
            }
            R.id.tv_management -> {
                showUserWithList()
            }
        }
    }

    private fun loginCheck(){
        val userService = ServiceCreator.create<UserService>()
        val userPhone = et_phone?.text.toString()
        val userPassword = et_password?.text.toString()
        userService.login(userPhone,userPassword).enqueue(object :
            Callback<Int> {
            override fun onResponse(call: Call<Int>,
                                    response: Response<Int>
            ) {
                val id = response.body()

                if (id == null) {
                    ToastUtil.show(this@LoginActivity,"登录失败，请联系管理员")
                }else{
                    if(id == 0) {
                        val builder = AlertDialog.Builder(this@LoginActivity)
                        builder.setTitle("登录失败")
                        builder.setMessage("密码错误，请重新登录")
                        builder.setPositiveButton("确定", null)
                        builder.create().show()
                    }
                    else {
                        //保存用户信息到数据库
                        if(userDao?.queryByPhone(userPhone) != null){
                            userDao?.update(
                                User(
                                    userPhone,
                                    userPassword,
                                    ck_remember?.isChecked == true
                                )
                            )
                        }else {
                            userDao?.insert(
                                User(
                                    userPhone,
                                    userPassword,
                                    ck_remember?.isChecked == true
                                )
                            )
                        }
                        //跳转到商品界面
                        app?.userId = id
                        val intent = Intent(this@LoginActivity,MallActivity::class.java)
                        /*val bundle = Bundle()
                        bundle.putInt("id",id)
                        intent.putExtras(bundle)*/
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
                        startActivity(intent)
                    }
                }

            }
            override fun onFailure(call: Call<Int>, t: Throwable) {
                ToastUtil.show(this@LoginActivity,"网络异常，请联系管理员")
            }
        })
    }

    private fun updateButtonState() {
        val phoneIsEmpty = et_phone?.text.isNullOrEmpty()
        val passwordIsEmpty = et_password?.text.isNullOrEmpty()
        btn_login?.isEnabled = !phoneIsEmpty && !passwordIsEmpty
    }



    private fun showUserWithList() {
        val builder = AlertDialog.Builder(this)
        val dialogView = this.layoutInflater.inflate(R.layout.user_list, null)
        lv_user = dialogView.findViewById(R.id.lv_user)

        val adapter = UserListAdapter(this@LoginActivity,userList!!)
        lv_user?.adapter = adapter
        lv_user?.setOnItemClickListener(this)

        builder.setView(dialogView)
        dialog = builder.create()
        dialog?.show()
    }

    override fun onItemClick(parent: AdapterView<*>?, view: View?, position : Int, id: Long) {
        et_phone?.setText(userList?.get(position)?.phone)
        if(userList?.get(position)?.remember == true){
            et_password?.setText(userList?.get(position)?.password)
            ck_remember?.isChecked = true
        }else{
            et_password?.setText("")
            ck_remember?.isChecked = false
        }
        dialog?.dismiss()
    }
}